<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;

class ApiResponse
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($response instanceof JsonResponse) {
            $data = $response->getData(true);

            // 如果响应已经有正确的格式，就不要修改它
            if (isset($data['success']) && isset($data['data']) && isset($data['message'])) {
                return $response;
            }

            $formattedResponse = [
                'success' => !isset($data['error']),
                'data' => $data['data'] ?? $data,
                'message' => $data['message'] ?? 'Success',
                'timestamp' => now()->toISOString()
            ];

            if (isset($data['error'])) {
                $formattedResponse['error'] = $data['error'];
                unset($formattedResponse['data']);
            }

            $response->setData($formattedResponse);
        }

        return $response;
    }
}